# coding=utf-8
import os
import sys
import datetime
import json

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common.stats import MG_BIGBANG_COLL
from common.account.model.account import Account


def find_chn_null_users():
    users = set()
    user_data = MG_BIGBANG_COLL.user_stats.find({'$or': [{'chn': None}, {'aid': None}]}, {"_id": 1})
    for each in user_data:
        users.add(each['_id'])
    daily_data = MG_BIGBANG_COLL.daily_stats.find({'$or': [{'chn': None}, {'aid': None}]}, {"user_id": 1})
    for each in daily_data:
        users.add(each.get('user_id'))
    return users


def set_aid_chns(user_ids):
    for account in Account.query.filter(Account.id.in_(user_ids)):
        user_id = account.id
        chn = account.channel or "google"
        aid = json.loads(account.extend or '{}').get('aid', None)
        print user_id
        if chn:
            print MG_BIGBANG_COLL.user_stats.update({"_id": user_id, "chn": None}, {"$set": {"chn": chn}})
            print MG_BIGBANG_COLL.daily_stats.update({"user_id": user_id, "chn": None}, {"$set": {"chn": chn}}, multi=True)
        if aid:
            print MG_BIGBANG_COLL.user_stats.update({"_id": user_id, "aid": None}, {"$set": {"aid": aid}})
            print MG_BIGBANG_COLL.daily_stats.update({"user_id": user_id, "aid": None}, {"$set": {"aid": aid}}, multi=True)


def main():
    user_ids = find_chn_null_users()
    set_aid_chns(user_ids)


if __name__ == "__main__":
    main()
